package leetcode;

import java.util.*;

public class Lc692_2 {



    public List<String> topKFrequent(String[] words, int k) {

        HashMap<String, Integer> map = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            int cnt = map.getOrDefault(words[i], 0);
            map.put(words[i], ++cnt);
        }
        PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>( (o1, o2) -> {
//            if (o1.getValue() == o2.getValue())
            if (o1.getValue().equals(o2.getValue())) //Integer的包装类型比较范围在-128~127之外会有问题，因为此范围之外的值在堆中创建
                return o1.getKey().compareTo(o2.getKey());
            return o2.getValue() - o1.getValue();
        });
        for (Map.Entry en: map.entrySet()) {
            pq.offer(en);
            if (pq.size() > k)
                pq.poll();
        }
        ArrayList<String> ans = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            ans.add(pq.poll().getKey());
        }
        return ans;
    }


    //基本类型的包装类型比较是否相等要用equals()!!!
    public static void main(String[] args) {
        Integer a = 12;
        Integer b = 12;
        System.out.println(a == b); //true

        a = 128;
        b = 128;
        System.out.println(a == b); //false

        a = 127;
        b = 127;
        System.out.println(a == b); //true

        a = -128;
        b = -128;
        System.out.println(a == b); //true

        a = -129;
        b = -129;
        System.out.println(a == b); //false
        System.out.println(a.equals(b)); //true

    }

}
